<template>
  <div class="orderDetails_container" v-loading="loading">
    <h1>
      订单状态：
      <dict-tag :options="dict.type.order_order_status" :value="order.orderStatus"/>
    </h1>
    <el-divider></el-divider>
    <div class="orderDetails-orderInfo">
      <h2>买家信息:</h2>
      <span>登录账号：{{ order.memberName }}</span>
      <span>客户名称：{{ order.purchaserName }}</span>
      <span>收货人名称：{{ order.consigneeName }}</span>
      <span>收货电话：{{ order.consigneeMobile }}</span>
      <span>
        收件地址：{{
        order.consigneeProvince +
        order.consigneeCity +
        order.consigneeCounty +
        order.consigneeDetail
        }}
      </span>
    </div>
    <div class="orderDetails-orderInfo">
      <h2>支付与配送信息:</h2>
      <span class="dict-tag">
        支付方式：
        {{
        order.paymentMethod === "WECHAT"
        ? "微信支付"
        : order.paymentMethod === "ALIPAY"
        ? "支付宝支付"
        : order.paymentMethod === "DINPAY"
        ? "智付"
        : order.paymentMethod === "WALLET"
        ? "账户余额"
        : order.paymentMethod === "BANK_TRANSFER"
        ? "线下公账交易"
        : ""
        }}
      </span>
      <span class="dict-tag">
        支付通道：
        {{
        order.paymentChannel === "WECHAT"
        ? "微信支付"
        : order.paymentChannel === "ALIPAY"
        ? "支付宝支付"
        : order.paymentChannel === "DINPAY"
        ? "智付"
        : order.paymentChannel === "WALLET"
        ? "账户余额"
        : order.paymentChannel === "BANK_TRANSFER"
        ? "线下公账交易"
        : ""
        }}
      </span>
      <span class="dict-tag">
        支付状态：
        <dict-tag :options="dict.type.order_pay_status" :value="order.payStatus"/>
      </span>
      <span>送货方式：快递/物流</span>
      <span>物流公司：{{ order.logisticsName }}</span>
      <span>物流单号：{{ order.logisticsNo }}</span>
    </div>
    <div class="orderDetails-orderInfo">
      <h2>订单信息:</h2>
      <span>订单编号：{{ order.sn }}</span>
      <span>创建日期：{{ order.createTime }}</span>
      <p>卖家留言：{{ order.remark }}</p>
    </div>

    <div class="tableOrderList">
      <h3>商品清单:</h3>
      <el-table border :data="order.orderItems" style="width: 100%">
        <el-table-column label="序号" align="center" type="index"></el-table-column>
        <el-table-column label="商品编码" align="center" prop="identifier">
          <template slot-scope="scope">
            <div>
              {{ scope.row.identifier
              }}
              <span
                style="color: red; font-size: 10px"
                v-if="scope.row.ephedrine"
              >麻</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" width="200" align="center" prop="name"></el-table-column>
        <el-table-column label="生产企业" width="200" align="center" prop="manufacturer"></el-table-column>
        <el-table-column label="批准文号" width="200" align="center" prop="approvalNo"></el-table-column>
        <el-table-column label="商品规格" align="center" prop="simpleSpecs"></el-table-column>
        <el-table-column label="活动" align="center" prop="promotionType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.app_promotion_type" :value="scope.row.promotionType"/>
          </template>
        </el-table-column>
        <el-table-column label="商品原价" align="center" prop="unitPrice"></el-table-column>
        <el-table-column label="销售价格" align="center" prop="goodsPrice">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.goodsPrice"
              :disabled="order.innerStatus = 'PACKAGED'&& order.payStatus != 'UNPAID'"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="订购数量" align="center" prop="num">
          <template slot-scope="scope">
            <div
              :style="{
                color: scope.row.num > scope.row.quantity ? 'red' : 'black',
              }"
            >
              <el-input
                v-model="scope.row.num"
                :disabled="order.innerStatus = 'PACKAGED'&& order.payStatus != 'UNPAID'"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="出库数量" align="center" prop="outboundNum"></el-table-column>
        <el-table-column label="小计" align="center" prop="subTotal">
          <template slot-scope="scope">{{ (scope.row.goodsPrice * scope.row.num).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="200"
          fixed="right"
        >
          <template slot-scope="scope" v-if="scope.row.roleId !== 1">
            <el-button
              size="mini"
              type="text"
              @click="handleEditTable(scope.row)"
              v-hasPermi="['order:order:query']"
            >修改</el-button>

            <el-button
              size="mini"
              type="text"
              @click="deleteOrderTable(scope.row)"
              v-hasPermi="['order:order:query']"
            >删除</el-button>

            <el-button
              size="mini"
              type="text"
              @click="loseOrderTable(scope.row)"
              v-hasPermi="['order:order:query']"
            >取消优惠券</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="p">
        <span>商品金额：{{ order.goodsPrice }}</span>
        <span>配送费用：{{ order.freightPrice }}</span>
        <span>优惠金额：{{ order.discountPrice }}</span>
        <span>优惠券金额：{{ order.couponPrice }}</span>
        <span>支付金额：{{ order.flowPrice }}</span>
      </div>
    </div>

    <div class="issueOrderList" v-if="order.innerStatus === 'PACKAGED'">
      <el-divider></el-divider>
      <h3>
        出库单号:
        {{
        issue.outboundOrderItems &&
        issue.outboundOrderItems[0].outboundOrderSn
        }}
      </h3>
      <el-table border v-loading="loading" :data="issue.outboundOrderItems" style="width: 100%">
        <el-table-column label="序号" align="center" type="index"></el-table-column>
        <el-table-column label="商品编号" align="center" prop="identifier"></el-table-column>
        <el-table-column label="商品名称" width="450" align="center" prop="goodsName"></el-table-column>
        <el-table-column label="生产企业" width="450" align="center" prop="manufacturer"></el-table-column>
        <el-table-column label="商品规格" align="center" prop="simpleSpecs"></el-table-column>
        <el-table-column label="有效期至" align="center" prop="expiryDate"></el-table-column>
        <el-table-column label="销售价格" align="center" prop="goodsPrice"></el-table-column>
        <el-table-column label="出库数量" align="center" prop="num"></el-table-column>
        <el-table-column label="小计" align="center" prop="subTotal"></el-table-column>
      </el-table>
      <div class="p">
        <span class="dict-tag">
          支付状态：
          <dict-tag :options="dict.type.order_pay_status" :value="order.payStatus"/>
        </span>
        <span>出库单金额：{{ issue.flowPrice }}</span>
      </div>
    </div>

    <div class="order_status">
      <div>
        <el-button
          type="primary"
          @click="openPresentView"
          v-hasPermi="['order:orderItem:presents:add']"
          v-if="order.innerStatus != 'PACKAGED'"
        >添加赠品</el-button>
        <el-button
          type="primary"
          @click="openPresentViewa"
          v-hasPermi="['order:orderItem:presents:add']"
          v-if="order.innerStatus != 'PACKAGED'&& order.payStatus === 'UNPAID' "
        >添加商品</el-button>
        <el-button
          type="primary"
          @click="openUpdateFreightPriceViewaaa"
          v-hasPermi="['order:orderItem:presents:add']"
          v-if="order.innerStatus != 'PACKAGED'&& order.payStatus === 'UNPAID' "
        >修改运费</el-button>
        <el-button
          type="primary"
          @click="openCouponView"
          v-hasPermi="['order:orderItem:presents:add']"
          v-if="order.innerStatus != 'PACKAGED'&& order.payStatus === 'UNPAID' "
        >添加优惠券</el-button>
        <el-button
          type="warning"
          @click="handleRePush"
          v-hasPermi="['order:order:innerStatus:edit']"
          v-if="
            order.innerStatus === 'PUSHED' ||
            order.innerStatus === 'ACCEPTANCE' ||
            order.innerStatus === 'PACKAGED'
          "
        >重新推送</el-button>
      </div>

      <!-- 未支付 -->
      <div
        v-if="
          (order.payStatus === 'UNPAID' ||
            order.payStatus === 'UNDETERMINED') &&
          (order.orderStatus === 'UNPAID' || order.orderStatus === 'CANCELLED')
        "
      >
        <!-- 选择支付方式 -->
        支付方式：
        <el-select v-model="valuetype" style="width: 150px">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.name"
            :value="item.method"
          ></el-option>
        </el-select>
        <!-- 支付单号 -->
        流水号：
        <el-input v-model="payOrderNumber" style="width: 250px; margin: 30px 0"></el-input>
      </div>

      <!-- 未发货 -->
      <div v-if="order.orderStatus === 'UNDELIVERED'">
        <!-- 物流公司 -->
        物流公司：
        <el-select v-model="valuetype" style="width: 150px">
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.name"
            :value="item.code"
          ></el-option>
        </el-select>
        <!-- 物流单号 -->
        物流单号：
        <el-input v-model="payOrderNumber" style="width: 250px; margin: 30px 0"></el-input>
      </div>

      <!-- 订单 取消 -->
      <el-button
        type="danger"
        @click="orderCancel"
        v-hasPermi="['order:order:cancel']"
        :disabled="order.orderStatus != 'UNPAID'"
      >取消订单</el-button>

      <el-button
        type="danger"
        @click="openUpdateFreightPriceView"
        v-hasPermi="['order:order:freightPrice:edit']"
        v-show="
          order.orderStatus === 'UNPAID' || order.orderStatus === 'CANCELLED'
        "
      >改运费</el-button>

      <!-- 订单 支付待确认 -->
      <!--
      <el-button type="primary" @click="unpayed" :disabled="order.payStatus !== 'UNDETERMINED'"
        v-hasPermi="['order:order:payment:edit']">
        未支付
      </el-button>
      -->

      <!-- 订单 未支付 -->
      <el-button
        type="primary"
        @click="payed"
        :disabled="
          order.orderStatus !== 'UNPAID' && order.orderStatus !== 'CANCELLED'
        "
        v-hasPermi="['order:order:payment:edit']"
      >已支付</el-button>

      <!-- 订单 未发货 -->
      <el-button
        type="success"
        @click="shipped"
        :disabled="order.orderStatus !== 'UNDELIVERED'"
        v-hasPermi="['order:order:deliver:edit']"
      >已发货</el-button>

      <!-- 订单 未收货 -->
      <!-- :disabled="order.orderStatus !== 'DELIVERED'" -->
      <el-button
        type="warning"
        @click="completed"
        v-hasPermi="['order:order:status:edit']"
        :disabled="order.orderStatus === 'COMPLETED'"
      >已收货</el-button>

      <!-- 订单退款 -->
      <el-button
        type="danger"
        @click="openOrderRefundView"
        v-hasPermi="['order:afterSale:add']"
        :disabled="
          order.payStatus != 'PAID' && order.payStatus != 'PARTIAL_REFUND'
        "
      >退款</el-button>
    </div>

    <!-- 订单退款 的商品数量 -->
    <el-dialog
      v-dialogDragWidth
      v-dialogDragHeight
      v-dialogDrag
      title="创建售后单"
      :visible.sync="orderRefundView"
      width="80%"
    >
      <div class="tableOrderList">
        <el-table border :data="afterSaleOrder.orderItems">
          <el-table-column label="序号" align="center" type="index"></el-table-column>
          <el-table-column label="商品编码" align="center" prop="identifier"/>
          <el-table-column label="商品名称" width="200" align="center" prop="name"></el-table-column>
          <el-table-column label="生产企业" width="200" align="center" prop="manufacturer"></el-table-column>
          <el-table-column label="批准文号" width="150" align="center" prop="approvalNo"></el-table-column>
          <el-table-column label="商品规格" align="center" prop="simpleSpecs"></el-table-column>
          <el-table-column label="销售价格" align="center" prop="goodsPrice"></el-table-column>
          <el-table-column label="订购数量" align="center" prop="orderItemNum">
            <template slot-scope="scope">
              <font
                :style="{
                  color:
                    scope.row.orderItemNum > scope.row.quantity
                      ? 'red'
                      : 'black',
                }"
              >{{ scope.row.orderItemNum }}</font>
              <font
                v-if="scope.row.returnGoodsNumber > 0"
                style="color: coral"
              >-{{ scope.row.returnGoodsNumber }}</font>
            </template>
          </el-table-column>
          <el-table-column label="出库数量" align="center" prop="outboundNum"></el-table-column>
          <el-table-column label="退款数量" align="center" prop="num" width="150px">
            <template slot-scope="scope">
              <el-input-number
                style="width: 120px"
                v-model="scope.row.num"
                @blur="
                  refundNum(scope.row, scope.row.orderItemNum, scope.row.num)
                "
                :min="0"
                :max="scope.row.orderItemNum"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="小计" align="center" prop="subTotal">
            <template slot-scope="scope">{{ (scope.row.goodsPrice * scope.row.num).toFixed(2) }}</template>
          </el-table-column>
        </el-table>
      </div>
      <div class="p">
        <span>商品金额：{{ afterSaleOrder.goodsPrice }}</span>
        <span>配送费用：{{ afterSaleOrder.freightPrice }}</span>
        <span>优惠金额：{{ afterSaleOrder.discountPrice }}</span>
        <span>优惠券金额：{{ afterSaleOrder.couponPrice }}</span>
        <span>支付金额：{{ afterSaleOrder.flowPrice }}</span>
      </div>
      <div class="p">
        <span>
          退差价：
          <el-input v-model="afterSaleOrder.updatePrice" placeholder="请输入差价总金额" style="width: 80px"></el-input>
        </span>
        <span>退款金额：{{ refundPrice }}</span>
        <span v-show="afterSaleOrder.freightPrice > 0">
          退运费
          <el-checkbox v-model="refundFreightFlag"></el-checkbox>
        </span>
        <span>
          <el-button type="danger" size="mini" @click="fullRefund">整单退款</el-button>
        </span>
        <span>
          售后原因：
          <el-input v-model="afterSaleOrder.reason" placeholder="请输入售后原因" style="width: 300px"/>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderRefundView = false">取 消</el-button>
        <el-button type="primary" @click="orderRefund">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 送赠品对话框 -->
    <el-dialog
      v-dialogDragWidth
      v-dialogDragHeight
      v-dialogDrag
      title="添加赠品"
      :visible.sync="openPresentFlag"
      width="1350px"
      append-to-body
    >
      <div class="gifts">
        <div class="left">
          赠品编码:
          <el-input v-model="presentSkuListForm.identifier" style="width: 120px" clearable></el-input>赠品名称:
          <el-input v-model="presentSkuListForm.goodsName" style="width: 200px" clearable></el-input>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handlePresentList"
            size="mini"
            style="margin: 0 0 20px 20px"
          >搜索</el-button>
          <el-table :data="presentSkuList" border>
            <el-table-column label="赠品编码" prop="identifier" width="120" align="center"></el-table-column>
            <el-table-column label="赠品名称" prop="goodsName" width="260" align="left"></el-table-column>
            <el-table-column label="规格" prop="simpleSpecs" width="80" align="center"></el-table-column>
            <el-table-column label="库存" prop="quantity" width="80" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  v-show="scope.row.addFlag"
                  @click="handleAddPresent(scope.row)"
                >添加</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="parseInt(presentSkuListForm.total) > 0"
            :total="parseInt(presentSkuListForm.total)"
            :page.sync="presentSkuListForm.pageNum"
            :limit.sync="presentSkuListForm.pageSize"
            @pagination="handlePresentList"
          />
        </div>

        <div class="right">
          赠品编码:
          <el-input v-model="giftSkuListForm.identifier" style="width: 120px" clearable></el-input>赠品名称:
          <el-input v-model="giftSkuListForm.goodsName" style="width: 200px" clearable></el-input>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleGiftList"
            size="mini"
            style="margin: 0 0 20px 20px"
          >搜索</el-button>
          <el-table :data="filterGiftsList" border>
            <el-table-column label="赠品编码" prop="identifier" width="120" align="center"></el-table-column>
            <el-table-column label="赠品名称" prop="goodsName" width="260" align="left"></el-table-column>
            <el-table-column label="规格" prop="simpleSpecs" width="80" align="center"></el-table-column>
            <el-table-column label="添加数量" prop="num" width="100" align="center">
              <template slot-scope="scope">
                <el-input type="number" min="1" v-model="scope.row.num"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" @click="delGiftsItem(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="parseInt(giftSkuListForm.total) > 0"
            :total="parseInt(giftSkuListForm.total)"
            :page.sync="giftSkuListForm.pageNum"
            :limit.sync="giftSkuListForm.pageSize"
            @pagination="handleGiftList"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="abandonPresent">取 消</el-button>
        <el-button type="primary" v-show="giftsList.length > 0" @click="submitPresent">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 加商品对话框 -->
    <el-dialog
      v-dialogDragWidth
      v-dialogDragHeight
      v-dialogDrag
      title="添加商品"
      :visible.sync="openPresentFlaga"
      width="1350px"
      append-to-body
    >
      <div class="gifts">
        <div class="left">
          商品编码:
          <el-input v-model="presentSkuListForma.identifier" style="width: 120px" clearable></el-input>商品名称:
          <el-input v-model="presentSkuListForma.goodsName" style="width: 200px" clearable></el-input>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handlePresentLista"
            size="mini"
            style="margin: 0 0 20px 20px"
          >搜索</el-button>
          <el-table :data="presentSkuList" border>
            <el-table-column label="商品编码" prop="identifier" width="100" align="center"></el-table-column>
            <el-table-column label="商品名称" prop="goodsName" width="220" align="left"></el-table-column>
            <el-table-column label="原价" prop="price" width="100" align="center"></el-table-column>
            <el-table-column label="库存" prop="quantity" width="80" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  v-show="scope.row.addFlag"
                  @click="handleAddPresenta(scope.row)"
                  :disabled="scope.row.quantity==0"
                >添加</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="parseInt(presentSkuListForma.total) > 0"
            :total="parseInt(presentSkuListForma.total)"
            :page.sync="presentSkuListForma.pageNum"
            :limit.sync="presentSkuListForma.pageSize"
            @pagination="handlePresentLista"
          />
        </div>

        <div class="right">
          商品编码:
          <el-input v-model="giftSkuListForm.identifier" style="width: 120px" clearable></el-input>商品名称:
          <el-input v-model="giftSkuListForm.goodsName" style="width: 200px" clearable></el-input>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleGiftLista"
            size="mini"
            style="margin: 0 0 20px 20px"
          >搜索</el-button>
          <el-table :data="filterGiftsList" border>
            <el-table-column label="商品编码" prop="identifier" width="100" align="center"></el-table-column>
            <el-table-column label="商品名称" prop="goodsName" width="220" align="left"></el-table-column>
            <el-table-column label="规格" prop="simpleSpecs" width="80" align="center"></el-table-column>
            <el-table-column label="销售价格" prop="price" width="100" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" :disabled="scope.row.status"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="订购数量" prop="num" width="85" align="center">
              <template slot-scope="scope">
                <el-input min="1" v-model="scope.row.num"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" @click="delGiftsItema(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="abandonPresenta">取 消</el-button>
        <el-button type="primary" v-show="giftsList.length > 0" @click="submitPresenta">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 改运费对话框 -->
    <el-dialog
      v-dialogDragWidth
      v-dialogDragHeight
      v-dialogDrag
      title="修改运费"
      :visible.sync="updateFreightPriceView"
      width="350px"
      append-to-body
    >
      运费：
      <el-input-number v-model="freightPrice"></el-input-number>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFreightPriceView = false">取 消</el-button>
        <el-button type="primary" @click="updateFreightPrice">确 定</el-button>
      </div>
    </el-dialog>
    <!--未支付订单改运费 -->
    <el-dialog
      v-dialogDragWidth
      v-dialogDragHeight
      v-dialogDrag
      title="修改运费"
      :visible.sync="updateFreightPriceViewaaa"
      width="350px"
      append-to-body
    >
      运费：
      <el-input-number v-model="freightPrice"></el-input-number>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFreightPriceViewaaa = false">取 消</el-button>
        <el-button type="primary" @click="updateFreightPriceaaa">确 定</el-button>
      </div>
    </el-dialog>
    <!--未支付订单添加优惠券 -->
    <el-dialog
      v-dialogDragWidth
      v-dialogDragHeight
      v-dialogDrag
      title="请选择要绑定优惠券的商品"
      :visible.sync="couponView"
      width="1300px"
      append-to-body
    >
      <div slot="footer" class="dialog-footer">
        <el-table
          border
          :data="order.orderItems"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" align="center" type="index"></el-table-column>
          <el-table-column label="商品编码" align="center" prop="identifier">
            <template slot-scope="scope">
              <div>
                {{ scope.row.identifier
                }}
                <span
                  style="color: red; font-size: 10px"
                  v-if="scope.row.ephedrine"
                >麻</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="200" align="center" prop="name"></el-table-column>
          <el-table-column label="生产企业" width="200" align="center" prop="manufacturer"></el-table-column>
          <el-table-column label="商品规格" align="center" prop="simpleSpecs"></el-table-column>
          <el-table-column label="活动" align="center" prop="promotionType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.app_promotion_type" :value="scope.row.promotionType"/>
            </template>
          </el-table-column>
          <el-table-column label="商品原价" align="center" prop="unitPrice"></el-table-column>
          <el-table-column label="销售价格" align="center" prop="goodsPrice"></el-table-column>
          <el-table-column label="订购数量" align="center" prop="num"></el-table-column>
          <el-table-column label="小计" align="center" prop="subTotal">
            <template slot-scope="scope">{{ (scope.row.goodsPrice * scope.row.num).toFixed(2) }}</template>
          </el-table-column>
        </el-table>

        <el-button @click="couponView = false">取 消</el-button>
        <el-button type="primary" @click="openOrderCouponView(ids)">确 定</el-button>
      </div>
    </el-dialog>

    <!--点确定查询用户优惠券 -->
    <el-dialog
      v-dialogDragWidth
      v-dialogDragHeight
      v-dialogDrag
      title="请选择要绑定的优惠券"
      :visible.sync="surecouponView"
      width="1300px"
      append-to-body
    >
      <div slot="footer" class="dialog-footer">
        <el-table
          ref="singleTable"
          :data="coupon"
          highlight-current-row
          @row-click="handleRowClick"
          style="width: 100%"
        >
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column property="couponId" label="优惠券编号" width="200"></el-table-column>
          <el-table-column property="price" label="优惠券价格" width="120"></el-table-column>
          <el-table-column property="consumeThreshold" label="优惠区间" width="120"></el-table-column>
        </el-table>
        <el-button type="primary" @click="giveCoupon">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOrderInfos,
  getOrderIssueInfos,
  updOrderStatus,
  updOrderPayed,
  updateInnerStatus,
  getPayList,
  getLogisticsList,
  updLogistics,
  updUnpay,
  updPay,
  cancelOrder,
  addPresents,
  updFreightPrice
} from "@/api/order/order.js";
import { addAfterSale } from "@/api/order/afterSale.js";
import { listGoodsSku } from "@/api/goods/goods";
import {
  choiceSpecialty,
  insertSpecialty,
  updateSpecialty,
  deleteOrderSpecialty,
  freightSpecialty,
  loseOrderSpecialty,
  getIDSpecialty,
  giveSpecialty
} from "@/api/goods/specialty";
export default {
  name: "OrderDetail",
  dicts: [
    "order_order_status",
    "order_pay_status",
    "order_payment_method",
    "app_promotion_type"
  ],
  data() {
    return {
      orderId: undefined,
      // 列表的行数据
      order: "",
      coupon: [],
      currentRow: null,
      ids: [],
      issue: "",
      ids: [],
      loading: true,
      valuetype: "",
      options: [],
      payOrderNumber: "",
      orderRefundView: false,
      afterSaleOrder: {
        updatePrice: 0,
        reason: "客户取消订单"
      },
      refundFreightFlag: false,
      openPresentFlag: false,
      openPresentFlaga: false,
      presentSkuList: [],
      presentSkuListForm: {
        total: "",
        pageNum: 1,
        pageSize: 10,
        identifier: "",
        goodsName: "",
        barCode: "",
        marketEnable: "",
        goodsType: "GIFT",
        paramMap: {}
      },
      listCoupon: {
        pageNum: 1,
        pageSize: 10,
        memberCouponStatus: "NEW",
        memberId: ""
      },
      presentSkuListForma: {
        total: "",
        pageNum: 1,
        pageSize: 10,
        identifier: "",
        goodsName: "",
        barCode: "",
        marketEnable: "",
        goodsType: "NORMAL",
        paramMap: {}
      },
      giftSkuListForm: {
        total: "",
        pageNum: 1,
        pageSize: 10,
        identifier: "",
        goodsName: ""
      },
      giftsList: [],
      filterGiftsList: [],
      updateFreightPriceView: false,
      updateFreightPriceViewaaa: false,
      couponView: false,
      surecouponView: false,
      freightPrice: 0
    };
  },
  computed: {
    refundPrice() {
      let a = 0;
      for (const key in this.afterSaleOrder.orderItems) {
        if (this.afterSaleOrder.orderItems[key].num > 0) {
          a +=
            this.afterSaleOrder.orderItems[key].num *
            this.afterSaleOrder.orderItems[key].goodsPrice;
        }
      }

      //运费
      if (this.refundFreightFlag) {
        a += this.afterSaleOrder.freightPrice;
      }

      return a.toFixed(2);
    }
  },
  created() {
    this.orderId = this.$route.params && this.$route.params.orderId;
    this.getOrderDetail();
  },
  methods: {
    fullRefund() {
      if ("退差价" === this.afterSaleOrder.reason) {
        this.afterSaleOrder.reason = "客户取消订单";
      }
      this.refundFreightFlag = true;
      this.afterSaleOrder.orderItems.forEach(i => {
        i.num = i.orderItemNum;
      });
    },
    refundNum(row, orderItemNum, num) {
      if (parseInt(orderItemNum) < parseInt(num)) {
        row.num = row.orderItemNum;
      }
    },

    getOrderDetail() {
      this.loading = true;

      getOrderInfos(this.orderId).then(res => {
        if (res.code === 200) {
          this.order = res.data;
          this.afterSaleOrder = this.deepCopy(this.order);
          this.afterSaleOrder.refundFreightFlag = false;

          this.loading = false;
          // 支付方式
          if (
            this.order.orderStatus === "UNPAID" ||
            this.order.orderStatus === "CANCELLED"
          ) {
            getPayList().then(res => {
              if (res.code === 200) {
                this.options = res.data;
                this.$delete(this.options, 3);
                this.valuetype = "BANK_TRANSFER";
              }
            });
          }
          // 物流公司
          if (this.order.orderStatus === "UNDELIVERED") {
            getLogisticsList().then(res => {
              if (res.code === 200) {
                this.options = res.data;
                this.valuetype = "JD";
              }
            });
          }
          // 出库单
          if (this.order.innerStatus === "PACKAGED") {
            getOrderIssueInfos(this.order.id).then(reds => {
              if (reds.code === 200) {
                this.issue = reds.data;

                this.issue.outboundOrderItems.forEach(outboundItem => {
                  this.order.orderItems.forEach(orderItem => {
                    if (!orderItem.outboundNum) {
                      orderItem.outboundNum = 0;
                    }
                    if (
                      orderItem.identifier == outboundItem.identifier &&
                      orderItem.goodsPrice == outboundItem.goodsPrice
                    ) {
                      if (orderItem.outboundNum < orderItem.num) {
                        orderItem.outboundNum += outboundItem.num;
                      }
                    }
                  });
                });
                this.loading = false;
              }
            });
          }
        }
      });
    },
    // 深克隆
    deepCopy(value) {
      if (value instanceof Function) return value;
      else if (value instanceof Array) {
        var newValue = [];
        for (let i = 0; i < value.length; ++i)
          newValue[i] = this.deepCopy(value[i]);
        return newValue;
      } else if (value instanceof Object) {
        var newValue = {};
        for (let i in value) newValue[i] = this.deepCopy(value[i]);
        return newValue;
      }
      return value;
    },
    //取消订单
    orderCancel() {
      const _this = this;
      this.$modal.confirm("确认取消订单吗？").then(function() {
        cancelOrder(_this.order.id, { cancelReason: "运营取消订单" }).then(
          res => {
            _this.getOrderDetail();
            _this.$modal.msgSuccess("取消订单成功");
          }
        );
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    // 订单退款 订单详情
    openOrderRefundView() {
      this.afterSaleOrder = this.deepCopy(this.order);
      // this.afterSaleOrder.updatePrice = 0;
      // this.afterSaleOrder.reason = "退差价";
      this.$set(this.afterSaleOrder, "updatePrice", 0);
      this.$set(this.afterSaleOrder, "reason", "退差价");
      this.afterSaleOrder.refundFreightFlag = false;

      this.afterSaleOrder.orderItems.forEach(orderItem => {
        orderItem.orderItemNum = parseInt(orderItem.num);

        orderItem.num = 0;
      });
      console.log(this.afterSaleOrder);
      this.refundFreightFlag = false;
      this.orderRefundView = true;
    },
    // 订单退款
    orderRefund() {
      if (this.afterSaleOrder.updatePrice < 0) {
        this.$modal.msgError("退差价不能为负数");
        return;
      }

      let applyRefundPrice = 0;

      let afterSaleItems = this.afterSaleOrder.orderItems
        .filter(i => {
          return i.num > 0;
        })
        .map(orderItem => {
          let subTotal = orderItem.num * orderItem.goodsPrice;
          applyRefundPrice += subTotal;

          return {
            orderItemSn: orderItem.sn,
            skuId: orderItem.skuId,
            goodsId: orderItem.goodsId,
            goodsPrice: orderItem.goodsPrice,
            num: orderItem.num,
            goodsImage: orderItem.image,
            goodsName: orderItem.name,
            pack: orderItem.pack,
            expirationDate: orderItem.expirationDate,
            manufacturer: orderItem.manufacturer,
            simpleSpecs: orderItem.simpleSpecs,
            subTotal: subTotal
          };
        });

      let refundFreightPrice = null;
      if (this.refundFreightFlag) {
        applyRefundPrice += this.afterSaleOrder.freightPrice;
        refundFreightPrice = this.afterSaleOrder.freightPrice;
      }

      const afterSale = {
        receipt: false,
        orderSn: this.afterSaleOrder.sn,
        tradeSn: this.afterSaleOrder.tradeSn,
        memberId: this.afterSaleOrder.memberId,
        memberName: this.afterSaleOrder.memberName,
        purchaserId: this.afterSaleOrder.purchaserId,
        purchaserName: this.afterSaleOrder.purchaserName,
        storeId: this.afterSaleOrder.storeId,
        storeName: this.afterSaleOrder.storeName,
        reason: this.afterSaleOrder.reason,
        serviceType: "RETURN_MONEY",
        serviceStatus: "APPLY",
        auditRemark: "平台退款",
        refundWay: "ORIGINAL",
        flowPrice: this.afterSaleOrder.flowPrice,
        applyRefundPrice: applyRefundPrice,
        afterSaleItems: afterSaleItems
      };

      const _this = this;
      this.$modal
        .confirm('确认给订单"' + this.afterSaleOrder.sn + '退款"吗？')
        .then(function() {
          console.log(afterSale);

          addAfterSale(afterSale).then(function(res) {
            _this.orderRefundView = false;
            _this.$modal.msgSuccess("售后单创建成功");
          });
        });
      // const currentOrder = {
      //   id: this.order.id,
      //   cancelReason: '平台取消订单'
      // }
      // this.$modal.confirm('确认取消订单"' + this.order.sn + '"吗？')
      //   .then(function () {
      //     cancelOrder(currentOrder.id, currentOrder)
      //   })
    },
    unpayed() {
      const currentOrder = {
        id: this.order.id,
        paymentMethod: this.valuetype,
        receivableNo: this.payOrderNumber
      };
      const _this = this;
      this.$modal
        .confirm("确认订单" + this.order.sn + '"用户未支付吗？')
        .then(function() {
          updUnpay(currentOrder.id, currentOrder).then(res => {
            _this.getOrderDetail();
            _this.$modal.msgSuccess("设置订单未支付");
          });
        });
    },
    payed() {
      const currentOrder = {
        id: this.order.id,
        paymentMethod: this.valuetype,
        receivableNo: this.payOrderNumber
      };
      const _this = this;
      this.$modal
        .confirm("确认订单" + this.order.sn + '"用户已支付吗？')
        .then(function() {
          updPay(currentOrder.id, currentOrder).then(res => {
            _this.getOrderDetail();
            _this.$modal.msgSuccess("设置订单已支付");
          });
        });
    },
    // 修改为已发货
    shipped() {
      const currentOrder = {
        id: this.order.id,
        logisticsCode: this.valuetype,
        logisticsName: this.options.filter(i => i.code === this.valuetype)[0]
          .name,
        logisticsNo: this.payOrderNumber
      };
      const _this = this;
      this.$modal
        .confirm("确认订单" + this.order.sn + '"已发货了吗？')
        .then(function() {
          updLogistics(currentOrder.id, currentOrder).then(res => {
            _this.getOrderDetail();
            _this.$modal.msgSuccess("订单发货成功");
          });
        });
    },
    // 确认收货
    completed() {
      const currentOrder = { id: this.order.id, orderStatus: "DELIVERED" };
      const _this = this;
      this.$modal
        .confirm("确认订单" + this.order.sn + '"用户已收货了吗？')
        .then(function() {
          updOrderStatus(currentOrder.id, currentOrder).then(res => {
            _this.getOrderDetail();
            _this.$modal.msgSuccess("订单收货成功");
          });
        });
    },
    // 赠品添加时 数据源
    handlePresentList() {
      this.loading = true;
      if (this.presentSkuListForm.identifier) {
        this.presentSkuListForm.identifier = this.presentSkuListForm.identifier.trim();
      }
      if (this.presentSkuListForm.goodsName) {
        this.presentSkuListForm.goodsName = this.presentSkuListForm.goodsName.trim();
      }
      listGoodsSku(0, this.presentSkuListForm).then(response => {
        response.rows.forEach(item => {
          item.addFlag = true;
          for (let gift of this.giftsList) {
            if (gift.id === item.id) {
              item.addFlag = false;
              break;
            }
          }
        });
        this.presentSkuList = response.rows;

        this.presentSkuListForm.total = response.total;
        this.loading = false;
      });
    },
    //商品添加时 数据源
    handlePresentLista() {
      this.loading = true;
      if (this.presentSkuListForma.identifier) {
        this.presentSkuListForma.identifier = this.presentSkuListForma.identifier.trim();
      }
      if (this.presentSkuListForma.goodsName) {
        this.presentSkuListForma.goodsName = this.presentSkuListForma.goodsName.trim();
      }
      listGoodsSku(0, this.presentSkuListForma).then(response => {
        response.rows.forEach(item => {
          item.addFlag = true;
          for (let gift of this.giftsList) {
            if (gift.id === item.id) {
              item.addFlag = false;
              break;
            }
          }
        });
        this.presentSkuList = response.rows;

        this.presentSkuListForma.total = response.total;
        this.loading = false;
      });
    },
    //打开赠送赠品窗口
    openPresentView() {
      this.giftsList = [];
      this.filterGiftsList = [];
      this.handlePresentList();
      this.openPresentFlag = true;
    },
    handleAddPresent(row) {
      this.$set(row, "num", 1);
      this.giftsList.push(row);
      row.addFlag = false;

      let new_set = new Set(this.giftsList);
      this.giftsList = [...new_set];
      this.handleGiftList();
    },
    delGiftsItem(e) {
      let new_set = new Set(this.giftsList);
      new_set.delete(e);
      this.giftsList = [...new_set];
      e.addFlag = true;
      this.handleGiftList();
    },
    handleGiftList() {
      if (this.giftSkuListForm.identifier) {
        this.giftSkuListForm.identifier = this.giftSkuListForm.identifier.trim();
      }
      if (this.giftSkuListForm.goodsName) {
        this.giftSkuListForm.goodsName = this.giftSkuListForm.goodsName.trim();
      }

      this.filterGiftsList = this.giftsList
        .filter(item => {
          if (this.giftSkuListForm.identifier) {
            return (
              item.identifier.indexOf(this.giftSkuListForm.identifier) >= 0
            );
          }

          return true;
        })
        .filter(item => {
          if (this.giftSkuListForm.goodsName) {
            return item.goodsName.indexOf(this.giftSkuListForm.goodsName) >= 0;
          }

          return true;
        });

      this.giftSkuListForm.total = this.filterGiftsList.length;
    },
    //取消添加赠品
    abandonPresent() {
      this.openPresentFlag = false;
      this.giftsList = [];
    },
    //提交赠品
    submitPresent() {
      let presents = [];
      this.giftsList.forEach(item => {
        presents.push({
          skuId: item.id,
          num: item.num
        });
      });
      console.log(presents);
      const _this = this;
      this.$modal
        .confirm("确认添加赠品吗？")
        .then(function() {
          addPresents(_this.order.sn, presents).then(response => {
            _this.openPresentFlag = false;
            _this.$modal.msgSuccess("赠品添加成功");
            _this.getOrderDetail();
          });
        })
        .catch(function() {});
    },
    //打开添加商品窗口
    openPresentViewa() {
      this.giftsList = [];
      this.filterGiftsList = [];
      this.handlePresentLista();
      this.openPresentFlaga = true;
    },
    handleAddPresenta(row) {
      choiceSpecialty(row.identifier).then(response => {
        this.$set(row, "status", response.data);
      });

      this.$set(row, "num", 1);
      this.giftsList.push(row);

      row.addFlag = false;

      let new_set = new Set(this.giftsList);
      this.giftsList = [...new_set];
      this.handleGiftLista();
    },
    delGiftsItema(e) {
      let new_set = new Set(this.giftsList);
      new_set.delete(e);
      this.giftsList = [...new_set];
      e.addFlag = true;
      this.handleGiftLista();
    },
    handleGiftLista() {
      if (this.giftSkuListForm.identifier) {
        this.giftSkuListForm.identifier = this.giftSkuListForm.identifier.trim();
      }
      if (this.giftSkuListForm.goodsName) {
        this.giftSkuListForm.goodsName = this.giftSkuListForm.goodsName.trim();
      }

      this.filterGiftsList = this.giftsList
        .filter(item => {
          if (this.giftSkuListForm.identifier) {
            return (
              item.identifier.indexOf(this.giftSkuListForm.identifier) >= 0
            );
          }

          return true;
        })
        .filter(item => {
          if (this.giftSkuListForm.goodsName) {
            return item.goodsName.indexOf(this.giftSkuListForm.goodsName) >= 0;
          }

          return true;
        });

      this.giftSkuListForm.total = this.filterGiftsList.length;
    },
    //取消添加商品
    abandonPresenta() {
      this.openPresentFlaga = false;
      this.giftsList = [];
    },
    //提交商品
    submitPresenta() {
      let presents = [];
      this.giftsList.forEach(item => {
        presents.push({
          skuId: item.id,
          num: item.num,
          goodsPrice: item.price
        });
      });
      console.log(presents);
      const _this = this;
      this.$modal
        .confirm("确认添加商品吗？")
        .then(function() {
          insertSpecialty(_this.order.sn, presents).then(response => {
            _this.openPresentFlaga = false;
            _this.$modal.msgSuccess("商品添加成功");
            _this.getOrderDetail();
          });
        })
        .catch(function() {});
    },
    handleEditTable(row) {
      let presents = [];
      presents.push({
        id: row.id,
        num: row.num,
        goodsPrice: row.goodsPrice
      });
      const _this = this;
      this.$modal
        .confirm("确认修改该商品吗？")
        .then(function() {
          updateSpecialty(_this.order.sn, presents).then(response => {
            _this.$modal.msgSuccess("商品修改成功");
            _this.getOrderDetail();
          });
        })
        .catch(function() {});
    },
    deleteOrderTable(row) {
      const _this = this;
      this.$modal
        .confirm("确认删除该商品吗？")
        .then(function() {
          deleteOrderSpecialty(_this.order.sn, row.id).then(response => {
            _this.$modal.msgSuccess("商品删除成功");
            _this.getOrderDetail();
          });
        })
        .catch(function() {});
    },
    loseOrderTable(row) {
      const _this = this;
      this.$modal
        .confirm("确认取消该商品优惠券吗？")
        .then(function() {
          loseOrderSpecialty(row.id).then(response => {
            _this.$modal.msgSuccess("该商品优惠券取消成功");
            _this.getOrderDetail();
          });
        })
        .catch(function() {});
    },

    //订单重新推送到ERP
    handleRePush() {
      const _this = this;
      this.$modal
        .confirm("确认将订单重新推送到ERP吗？")
        .then(function() {
          updateInnerStatus(_this.order.sn, { innerStatus: "RE_PUSH" }).then(
            response => {
              _this.$modal.msgSuccess("已重新推送订单到ERP");
            }
          );
        })
        .catch(function() {});
    },
    openUpdateFreightPriceView() {
      this.freightPrice = this.order.freightPrice;
      this.updateFreightPriceView = true;
    },
    openUpdateFreightPriceViewaaa() {
      this.freightPrice = this.order.freightPrice;
      this.updateFreightPriceViewaaa = true;
    },
    openCouponView() {
      this.couponView = true;
    },
    updateFreightPrice() {
      const _this = this;
      this.$modal
        .confirm("确认将订单的运费改为￥" + this.freightPrice + "吗？")
        .then(function() {
          updFreightPrice(_this.order.id, {
            freightPrice: this.freightPrice
          }).then(response => {
            _this.$modal.msgSuccess("运费修改成功");
            _this.updateFreightPriceView = false;
            _this.getOrderDetail();
          });
        })
        .catch(function() {});
    },
    //修改运费 点击确定执行接口
    updateFreightPriceaaa() {
      const _this = this;
      this.$modal
        .confirm("确认将订单的运费改为￥" + this.freightPrice + "吗？")
        .then(function() {
          freightSpecialty(_this.order.id, {
            freightPrice: _this.freightPrice
          }).then(response => {
            _this.$modal.msgSuccess("运费修改成功");
            _this.updateFreightPriceViewaaa = false;
            _this.getOrderDetail();
          });
        })
        .catch(function() {});
    },
    //添加优惠券 点击确定执行接口
    openOrderCouponView(ids) {
      this.ids = ids;
      let presents = {
        memberId: this.order.memberId,
        pageSize: 10,
        pageNum: 1,
        memberCouponStatus: "NEW"
      };
      let that = this;
      this.$modal
        .confirm("请选择合适的优惠券!")
        .then(function() {
          getIDSpecialty(presents).then(response => {
            that.coupon = response.rows;
          });
        })
        .catch(function() {});

      this.surecouponView = true;

      //.then(function() {
      //  freightSpecialty(_this.order.id, {
      //    freightPrice: this.freightPrice
      //    }).then(response => {
      //     _this.$modal.msgSuccess("运费修改成功");
      // _this.updateFreightPriceViewaaa = false;
      // _this.getOrderDetail();
      //   });
      //   })
      //   .catch(function() {});
    },
    //单选框
    handleRowClick(row, column, event) {
      this.currentRow = row;
    },
    giveCoupon() {
      const _this = this;
      let presents = {
        ids: this.ids,
        couponId: this.currentRow.couponId,
        couponPrice: this.currentRow.price
      };
      this.$modal
        .confirm("确定绑定此优惠券吗！")
        .then(function() {
          giveSpecialty(_this.order.memberId, _this.order.sn, presents).then(
            response => {
              _this.$modal.msgSuccess("优惠券已绑定");
              _this.getOrderDetail();
            }
          );
        })
        .catch(function() {});
      _this.surecouponView = false;
      _this.couponView = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.orderDetails_container {
  h1 {
    display: flex;
    margin: 30px 20px;
  }
  .orderDetails-orderInfo {
    padding: 0 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid rgba($color: #000000, $alpha: 0.1);
    span {
      margin: 10px 0;
      margin-right: 50px;
    }
  }
  .tableOrderList {
    padding: 0 20px;
    // overflow: hidden;
  }
  .issueOrderList {
    padding: 0 20px;
    // overflow: hidden;
  }
  .p {
    text-align: center;
    padding: 50px 0;
    span {
      margin-right: 50px;
    }
  }
  .dict-tag {
    div {
      display: inline;
    }
  }
  .order_status {
    padding-right: 100px;
    float: right;
    margin-bottom: 100px;
  }
}
::v-deep .el-dialog {
  top: 0;
  .tableOrderList {
    height: 500px;
    overflow-y: scroll;
  }
  .p {
    padding: 3px 0 0;
  }
}

.gifts {
  display: flex;
  max-height: 80vh;
  .left {
    width: 630px;
    margin-right: 10px;
    .item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 30px;
    }
    span:nth-child(1) {
      max-width: 70%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      cursor: pointer;
      color: tomato;
    }
  }
  .right {
    width: 680px;
  }
}
</style>
